﻿using Commons.ASPNETCore;
using Commons.DomainBase;
using IdentityService.Domain;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace IdentityService.Webapi.Controllers.UserAdmin
{
    [Route("Identity/[controller]/[action]")]
    [ApiController]
    public class UserAdminController : ControllerBase
    {
        private readonly IIdRepository repository;

        public UserAdminController( IIdRepository repository)
        {
            this.repository = repository;
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public async Task<Result> AddAdminUser(AddAdminUserRequest req)
        {

            User u = IdentityService.Domain.User.Create(req.UserName, "123456");
               u.CreateUserId= long.Parse(this.User.FindFirstValue(ClaimTypes.NameIdentifier));
                u.Name = req.UserName;
            //todo错误的方法
            (var result, User user, var password) = await repository.AddTeacherAsync(u);
            if (!result)
            {
                return Result.Fail();
            }
            return Result.Success();
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public async Task<Result> AddTeacherUser(AddTeacherUserRequest req)
        {

            User? u = await repository.FindByNameAsync(req.UserName);            
            if (u != null)
            {
                return Result.Fail(CodeType.HAVE_DATA);
            }

             u = IdentityService.Domain.User.Create(req.UserName,req.Password);
            u.CreateUserId = long.Parse(this.User.FindFirstValue(ClaimTypes.NameIdentifier));
            u.Name = req.Name;
            (var result, User user, var password) = await repository.AddTeacherAsync(u);
            if (!result)
            {
                return Result.Fail();
            }
            return Result.Success();
        }



        [HttpGet]
        public  Result FindAllUser()
        {
            var list = repository.FindAllUsers(long.Parse(this.User.FindFirstValue(ClaimTypes.NameIdentifier)));
            if (list == null)
            {
                return Result.Success(new List<User>());
            }
            return Result.Success(list);
        }
    }
}
